package marcel.media.video.youtube {

	import aze.motion.eaze;

	import marcel.debug.debuge;
	import marcel.media.video.youtube.events.YTEvent;
	import marcel.utils.IDestroyable;

	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLRequest;
	
	
	//__________________________________________________________ EVENTS
	[Event(name="onReady", type="marcel.media.video.youtube.events.YTEvent")]
	[Event(name="onError", type="marcel.media.video.youtube.events.YTEvent")]
	[Event(name="onStateChange", type="marcel.media.video.youtube.events.YTEvent")]
	[Event(name="onPlaybackQualityChange", type="marcel.media.video.youtube.events.YTEvent")]
	//__________________________________________________________ EVENTS
	
	
	/**
	 * Youtube Chromeless player Wrapper
	 * Allows you to manipulate the YT Chromeless player in a smooth and easy way
	 * 
	 * @author Nicolas CHESNE
	 */
	public class YTWrapper extends Sprite implements IDestroyable {
		
		private var player:Object;
		private var loader:Loader;
		private var _isReady:Boolean;
		
		public function YTWrapper(autoInit:Boolean = false, silentError:Boolean = true) {
			if(silentError)player = new Object();
			if(autoInit) init();
			mouseChildren = false;
		}
		
		
		//__________________________________________________________ PUBLIC
		
		/**
		 * Loads the YT Chromeless Player classes.
		 * Other method can't be called before you call this one and wait for a YTEvent.READY Event.
		 */		
		public function init():void {
			// The player SWF file on www.youtube.com needs to communicate with your host
			// SWF file. Your code must call Security.allowDomain() to allow this
			// communication.
//			Security.allowDomain("www.youtube.com");
			// This will hold the API player instance once it is initialized.
			
			// asset version
//			loader = Index(Plugin.plugin).getYTPlayer();
//			onLoaderInit();

			// classic version
			loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);
			loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));
		}
		//_________________________________________________ Queueing functions
		
		
		/**
		 * Loads the specified video's thumbnail and prepares the player to play the video.
		 * The player does not request the FLV until playVideo() or seekTo() is called.
		 * 
		 * @param videoId specifies the YouTube Video ID of the video to be played. In YouTube Data API video feeds, the <yt:videoid> tag specifies the ID.
		 * @param startSeconds accepts a float/integer and specifies the time from which the video should start playing when playVideo() is called. If you specify a startSeconds value and then call seekTo(), then the player plays from the time specified in the seekTo() call. When the video is cued and ready to play, the player will broadcast a video cued event (5).
		 * @param suggestedQuality specifies the suggested playback quality for the video. Please see the definition of the setPlaybackQuality function for more information about playback quality.

		 */
		public function cueVideoById(videoId:String, startSeconds:Number = 0, suggestedQuality:String = "medium"):void {
			player.cueVideoById(videoId, startSeconds, suggestedQuality);
		}
		
		/**
		 * 	Loads and plays the specified video.
		 * 		
		 * 	@param videoId specifies the YouTube Video ID of the video to be played. In YouTube Data API video feeds, the <yt:videoid> tag specifies the ID.
		 * 	@param startSeconds accepts a float/integer. If it is specified, then the video will start from the closest keyframe to the specified time.
		 * 	@param suggestedQuality specifies the suggested playback quality for the video. Please see the definition of the setPlaybackQuality function for more information about playback quality.
		 */
		public function loadVideoById(videoId:String, startSeconds:Number = 0, suggestedQuality:String = "medium"):void {
			player.loadVideoById(videoId, startSeconds, suggestedQuality);
		}
		
		/**
		 * Loads the specified video's thumbnail and prepares the player to play the video.
		 * The player does not request the FLV until playVideo() or seekTo() is called.
		 * 
		 * @param mediaContentUrl must be a fully qualified YouTube player URL in the format http://www.youtube.com/v/VIDEO_ID. In YouTube Data API video feeds, the url attribute of the <media:content> tag contains a fully qualified player URL when the tag's format attribute has a value of 5.
		 * @param startSeconds accepts a float/integer and specifies the time from which the video should start playing when playVideo() is called. If you specify startSeconds and then call seekTo(), then the player plays from the time specified in the seekTo() call. When the video is cued and ready to play, the player will broadcast a video cued event (5).
		 */
		public function cueVideoByUrl(mediaContentUrl:String, startSeconds:Number = 0):void {
			player.cueVideoByUrl(mediaContentUrl, startSeconds);
		}
		
		/**
		 * Loads and plays the specified video.
		 * 
		 * @param mediaContentUrl must be a fully qualified YouTube player URL in the format http://www.youtube.com/v/VIDEO_ID. In YouTube Data API video feeds, the url attribute of the <media:content> tag contains a fully qualified player URL when the tag's format attribute has a value of 5.
		 * @param startSeconds accepts a float/integer and specifies the time from which the video should start playing. If startSeconds (number can be a float) is specified, the video will start from the closest keyframe to the specified time.
		 */
		public function loadVideoByUrl(mediaContentUrl:String, startSeconds:Number = 0):void {
			player.loadVideoByUrl(mediaContentUrl, startSeconds);
		}
		
		/**
		 * Loads and plays the specified video. When the playlist is cued and ready to play, the player will broadcast a video cued event (5).
		 * 
		 * @param playlist specifies either a YouTube playlist ID or an array of YouTube video IDs. In YouTube Data API feeds, the <yt:playlistid> tag specifies a playlist ID, and the <yt:videoid> tag specifies a video ID.
		 * @param index specifies the index of the first video in the playlist that will play. The parameter uses a zero-based index, and the default parameter value is 0, so the default behavior is to load and play the first video in the playlist.
		 * @param startSeconds accepts a float/integer and specifies the time from which the first video in the playlist should start playing when the playVideo() function is called. If you specify a startSeconds value and then call seekTo(), then the player plays from the time specified in the seekTo() call. If you cue a playlist and then call the playVideoAt() function, the player will start playing at the beginning of the specified video.
		 * @param suggestedQuality specifies the suggested playback quality for the video. Please see the definition of the setPlaybackQuality function for more information about playback quality.
		 */
		public function cuePlaylist(playlist:*, index:Number = 0, startSeconds:Number = 0, suggestedQuality:String = "medium"):void {
			player.cuePlaylist(playlist, index, startSeconds, suggestedQuality);
		}
		
		/**
		 * This function loads the specified playlist and plays it.
		 * 
		 * @param playlist specifies either a YouTube playlist ID or an array of YouTube video IDs. In YouTube Data API feeds, the <yt:playlistid> tag specifies a playlist ID, and the <yt:videoid> tag specifies a video ID.
		 * @param index specifies the index of the first video in the playlist that will play. The parameter uses a zero-based index, and the default parameter value is 0, so the default behavior is to load and play the first video in the playlist.
		 * @param startSeconds accepts a float/integer and specifies the time from which the first video in the playlist should start playing.
		 * @param suggestedQuality specifies the suggested playback quality for the video. Please see the definition of the setPlaybackQuality function for more information about playback quality.
		 */
		public function loadPlaylist(playlist:*, index:Number = 0, startSeconds:Number = 0, suggestedQuality:String = "medium"):void {
			player;loadPlaylist(playlist, index, startSeconds, suggestedQuality);
		}
		
		//________________________________________________ Playback controls and player settings
		
		
		/**
		 * Plays the currently cued/loaded video. The final player state after this function executes will be playing (1).
		 * Note: YouTube only counts playbacks that are initiated through a native play button in either the embedded or chromeless player.
		 */
		public function playVideo():void {
			player.playVideo();
		}
		
		/**
		 * Pauses the currently playing video. The final player state after this function executes will be paused (2)
		 * unless the player is in the ended (0) state when the function is called, in which case the player state will not change.
		 */
		public function pauseVideo():void {
			player.pauseVideo();
		}
		
		/**
		 * Stops and cancels loading of the current video.
		 * This function should be reserved for rare situations when you know that the user will not be watching additional video in the player.
		 * If your intent is to pause the video, you should just call the pauseVideo function. If you want to change the video that the player is playing,
		 * you can call one of the queueing functions without calling stopVideo first.
		 * 
		 * Important: Unlike the pauseVideo function, which leaves the player in the paused (2) state, the stopVideo function
		 * could put the player into any not-playing state, including ended (0), paused (2), video cued (5) or unstarted (-1).
		 */
		public function stopVideo():void {
			player.stopVideo();
		}
		
		/**
		 * Seeks to a specified time in the video.
		 * 
		 * @param seconds identifies the time from which the video should start playing.
		 *         If the player has already buffered the portion of the video to which the user is advancing, then the player will start playing the video at the closest keyframe to the specified time. This behavior is governed by the seek() method of the Flash player's NetStream object. In practice, this means that the player could advance to a keyframe just before or just after the specified time. (For more information, see Adobe's documentation for the NetStream class.)
		 *         If the player has not yet buffered the portion of the video to which the user is seeking, then the player will start playing the video at the closest keyframe before the specified time.
		 * @param allowSeekAhead determines whether the player will make a new request to the server if the seconds parameter specifies a time outside of the currently buffered video data. We recommend that you set this parameter to <code>false</code> while the user is dragging the mouse along a video progress bar and then set the parameter to <code>true</code> when the user releases the mouse.
		 *     This approach lets the user scroll to different points of the video without requesting new video streams by scrolling past unbuffered points in the video. Then, when the user releases the mouse button, the player will advance to the desired point in the video, only requesting a new video stream if the user is seeking to an unbuffered point in the stream.
		 *     
		 * The final player state after this function executes will be playing (1) unless the value of the seconds parameter is greater than the video length, in which case the final player state will be ended (0).
		 */
		public function seekTo(seconds:Number, allowSeekAhead:Boolean = false):void {
			player.seekTo(seconds, allowSeekAhead);			
		}
		
		/**
		 * This function loads and plays the next video in the playlist.
		 * 
		 * If player.nextVideo() is called while the last video in the playlist is being watched, and the playlist is set to play continuously (loop), then the player will load and play the first video in the list.
		 * If player.nextVideo() is called while the last video in the playlist is being watched, and the playlist is not set to play continuously, then playback will end.
		 */
		public function nextVideo():void {
			player.nextVideo();
		}
		
		/**
		 * This function loads and plays the previous video in the playlist.
		 * 
		 * If player.previousVideo() is called while the first video in the playlist is being watched, and the playlist is set to play continuously (loop), then the player will load and play the last video in the list.
		 * If player.previousVideo() is called while the first video in the playlist is being watched, and the playlist is not set to play continuously, then the player will restart the first playlist video from the beginning.
		 */
		public function previousVideo():void {
			player.previousVideo();
		}
		
		/**
		 * This function loads and plays the specified video in the playlist.
		 * 
		 * @param index specifies the index of the video that you want to play in the playlist. The parameter uses a zero-based index, so a value of 0 identifies the first video in the list. If you have shuffled the playlist, this function will play the video at the specified position in the shuffled playlist.
		 */
		public function playVideoAt(index:Number):void {
			player.playVideoAt(index);
		}
		
		/**
		 * Mutes the player.
		 */
		public function mute():void {
			player.mute();
		}
		
		/**
		 * Unmutes the player.
		 */
		public function unMute():void {
			player.unMute();
		}
		
		/**
		 * Returns true if the player is muted, false if not.
		 */
		public function isMuted():Boolean {
			return player.isMuted();
		}
		
		/**
		 * Sets the volume. Accepts an integer between 0 and 100.
		 * 
		 * @param volume the player volume between 0 and 100.
		 */
		public function setVolume(volume:Number):void {
			player.setVolume(volume);
		}
		
		/**
		 * Implicit Getter for eaze tween and TweenMax compatibility
		 */
		public function get vol():Number {
			return getVolume();
		}
		
		/**
		 * Implicit Setter for eaze tween and TweenMax compatibility
		 */
		public function set vol(value:Number):void {
			setVolume(value);
		}
		
		/**
		 * Returns the player's current volume, an integer between 0 and 100. Note that getVolume() will return the volume even if the player is muted.
		 */
		public function getVolume():Number {
			return player.getVolume();
		}
		
		/**
		 * Sets the size in pixels of the player. This method should be used instead of setting the width and height properties of the MovieClip.
		 * Note that this method does not constrain the proportions of the video player, so you will need to maintain a 4:3 aspect ratio.
		 * The default size of the chromeless SWF when loaded into another SWF is 320px by 240px and the default size of the embedded player SWF is 480px by 385px.
		 * 
		 * @param width The video width in px
		 * @param height The video height in px
		 */
		public function setSize(width:Number, height:Number):void {
			player.setSize(Math.round(width), Math.round(height));
		}
		
		/**
		 * This function indicates whether the video player should continuously play a playlist or if it should stop playing after
		 * the last video in the playlist ends. The default behavior is that playlists do not loop.
		 * This setting will persist even if you load or cue a different playlist, which means that if you load a playlist,
		 * call the setLoop function with a value of true, and then load a second playlist, the second playlist will also loop.
		 * 
		 * @param loopPlaylists identifies the looping behavior.
		 * 		If the parameter value is <code>true</code>, then the video player will continuously play playlists. After playing the last video in a playlist, the video player will go back to the beginning of the playlist and play it again.
		 * 		If the parameter value is <code>false</code>, then playbacks will end after the video player plays the last video in a playlist.
		 */
		public function setLoop(loopPlaylists:Boolean):void {
			player.setLoop(loopPlaylists);
		}
		
		/**
		 * This function indicates whether a playlist's videos should be shuffled so that they play back in an order different from the one
		 * that the playlist creator designated. If you shuffle a playlist after it has already started playing, the list will be reordered
		 * while the video that is playing continues to play. The next video that plays will then be selected based on the reordered list.
		 * This setting will not persist if you load or cue a different playlist, which means that if you load a playlist,
		 * call the setShuffle function, and then load a second playlist, the second playlist will not be shuffled.
		 *     
		 * @param shufflePlaylist indicates whether YouTube should shuffle the playlist.
		 *     	If the parameter value is true, then YouTube will shuffle the playlist order. If you instruct the function to shuffle a playlist that has already been shuffled, YouTube will shuffle the order again.
		 *     	If the parameter value is false, then YouTube will change the playlist order back to its original order.
		 */
		public function setShuffle(shufflePlaylist:Boolean):void {
			player.setShuffle(shufflePlaylist);
		}
		
		//_________________________________________________ Playback Status
		
		/**
		 * Returns the number of bytes loaded for the current video.
		 */
		public function getVideoBytesLoaded():Number {
			return player.getVideoBytesLoaded();
		}
		
		/**
		 * Returns the size in bytes of the currently loaded/playing video or an approximation of the video's size.
		 * 
		 * Specifically, this function will approximate the total size of the video when the value of player.getVideoStartBytes() is greater than zero.
		 * The function needs to approximate the video's size because the video's actual size is only communicated to the player when the video
		 * starts from the beginning.
		 */
		public function getVideoBytesTotal():Number {
			return player.getVideoBytesTotal();
		}
		
		/**
		 * Returns the number of bytes the video file started loading from. Example scenario: the user seeks ahead to a point that hasn't loaded yet,
		 * and the player makes a new request to play a segment of the video that hasn't loaded yet.
		 */
		public function getVideoStartBytes():Number {
			return player.getVideoStartBytes();
		}
		
		/**
		 * Returns the state of the player. Possible values are unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5).
		 */
		public function getPlayerState():Number {
			return player.getPlayerState();
		}
		
		/**
		 * Returns the elapsed time in seconds since the video started playing.
		 */
		public function getCurrentTime():Number {
			return player.getCurrentTime();
		}
		
		//________________________________________________ Playback Quality
		
		/**
		 * This function retrieves the actual video quality of the current video.
		 * @return <code>undefined</code> if there is no current video.
		 * 			Possible return values are <code>highres</code>, <code>hd1080</code>, <code>hd720</code>, <code>large</code>, <code>medium</code> and <code>small</code>.
		 */
		public function getPlaybackQuality():String {
			return player.getPlaybackQuality();
		}
		
		/**
		 * This function sets the suggested video quality for the current video. The function causes the video to reload at its current position
		 * in the new quality. If the playback quality does change, it will only change for the video being played.
		 * Calling this function does not guarantee that the playback quality will actually change. However, if the playback quality does change,
		 * the onPlaybackQualityChange event will fire, and your code should respond to the event rather than the fact that it called
		 * the setPlaybackQuality function.
		 * 
		 * If you call the setPlaybackQuality function with a suggestedQuality level that is not available for the video,
		 * then the quality will be set to the next lowest level that is available.
		 * For example, if you request a quality level of large, and that is unavailable,
		 * then the playback quality will be set to medium (as long as that quality level is available).
		 * 
		 * @param suggestedQuality The suggestedQuality parameter value can be small, medium, large, hd720, hd1080, highres or default. We recommend that you set the parameter value to default, which instructs YouTube to select the most appropriate playback quality, which will vary for different users, videos, systems and other playback conditions.
		 */
		public function setPlaybackQuality(suggestedQuality:String):void {
			player.setPlaybackQuality(suggestedQuality);
		}
		
		/**
		 * This function returns the set of quality formats in which the current video is available. You could use this function to determine whether the video is available in a higher quality than the user is viewing, and your player could display a button or other element to let the user adjust the quality.
		 * Your client should not automatically switch to use the highest (or lowest) quality video or to any unknown format name. YouTube could expand the list of quality levels to include formats that may not be appropriate in your player context. Similarly, YouTube could remove quality options that would be detrimental to the user experience. By ensuring that your client only switches to known, available formats, you can ensure that your client's performance will not be affected by either the introduction of new quality levels or the removal of quality levels that are not appropriate for your player context.
		 * 
		 * @return an array of strings ordered from highest to lowest quality. Possible array element values are highres, hd1080, hd720, large, medium and small. This function returns an empty array if there is no current video.
		 */
		public function getAvailableQualityLevels():Array {
			return player.getAvailableQualityLevels();
		}
		
		//________________________________________________ Retrieving video information
		
		/**
		 * Returns the duration in seconds of the currently playing video. Note that getDuration() will return 0 until the video's metadata is loaded,
		 * which normally happens just after the video starts playing.
		 */
		public function getDuration():Number {
			return player.getDuration();
		}
		
		/**
		 * Returns the YouTube.com URL for the currently loaded/playing video.
		 */
		public function getVideoUrl():String {
			return player.getVideoUrl();
		}
		
		/**
		 * Returns the embed code for the currently loaded/playing video.
		 */
		public function getVideoEmbedCode():String {
			return player.getVideoEmbedCode();
		}
		
		
		//________________________________________________ Retrieving playlist information
		
		/**
		 * This function returns an array of the video IDs in the playlist as they are currently ordered. By default, this function will return video IDs
		 * in the order designated by the playlist owner. However, if you have called the setShuffle function to shuffle the playlist order,
		 * then the getPlaylist() function's return value will reflect the shuffled order.
		 */
		public function getPlaylist():Array {
			return player.getPlaylist();
		}
		
		/**
		 * This function returns the index of the playlist video that is currently playing.
		 * 
		 * If you have not shuffled the playlist, the return value will identify the position where the playlist creator placed the video. The return value uses a zero-based index, so a value of 0 identifies the first video in the playlist.
		 * If you have shuffled the playlist, the return value will identify the video's order within the shuffled playlist.
		 */
		public function getPlaylistIndex():Number {
			return player.getPlaylistIndex();
		}
		
		
		//________________________________________________ Mem Management
		
		/**
		 * This function destroys the player instance. It should be called before unloading the player SWF from your parent SWF.
		 * This function close the NetStream object.
		 */
		public function destroy():void {
			loader.content.removeEventListener("onReady", onPlayerReady);
			loader.content.removeEventListener("onError", onPlayerError);
			loader.content.removeEventListener("onStateChange", onPlayerStateChange);
			loader.content.removeEventListener("onPlaybackQualityChange", onVideoPlaybackQualityChange);
			removeChild(loader);
			
			try {
				stopVideo();
			}catch(e:Error){
				
			}
			
			///
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoaderInit);
			loader.unloadAndStop(true);
			loader = null;
			
			player.destroy();
			player = null;

			///
//			Index(Plugin.plugin).storeYTPlayer();
			///
			
		}
		
		
		//__________________________________________________________ PRIVATE & HANDLERS
		
		private function onLoaderInit(event:Event = null):void {
			loader.alpha = 0;
			addChild(loader);
			player = loader.content;
			
			loader.content.addEventListener("onError", onPlayerError);
			loader.content.addEventListener("onStateChange", onPlayerStateChange);
			loader.content.addEventListener("onPlaybackQualityChange", onVideoPlaybackQualityChange);
			
			try {
				setShuffle(false);
			} catch(e:Error){
				trace("player not ready");
				loader.content.addEventListener("onReady", onPlayerReady);
				return;
			}
			eaze(this).delay(.05).onComplete(onPlayerReady);
		}

		private function onPlayerReady(event:Event = null):void {
			// Event.data contains the event parameter, which is the Player API ID
//			trace("player ready:", Object(event).data);

			// Once this event has been dispatched by the player, we can use
			// cueVideoById, loadVideoById, cueVideoByUrl and loadVideoByUrl
			// to load a particular YouTube video.
			player = loader.content;
			_isReady = true;
			eaze(loader).to(1, {alpha:1});
			dispatchEvent(new YTEvent(YTEvent.READY, null));
		}

		private function onPlayerError(event:Event):void {
			// Event.data contains the event parameter, which is the error code
			debuge("YT_PLAY ERROR :: "+Object(event).data);
			dispatchEvent(new YTEvent(YTEvent.ERROR, Object(event).data));
		}

		private function onPlayerStateChange(event:Event):void {
			// Event.data contains the event parameter, which is the new player state
			dispatchEvent(new YTEvent(YTEvent.STATE_CHANGE, Object(event).data));
		}

		private function onVideoPlaybackQualityChange(event:Event):void {
			// Event.data contains the event parameter, which is the new video quality
			dispatchEvent(new YTEvent(YTEvent.QUALITY_CHANGE, Object(event).data));
		}

		public function get isReady():Boolean {
			return _isReady;
		}
	}
}
